package buco.http;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import buco.core.api.*;

@SuppressWarnings("serial")
public class FileServlet extends CompositionServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{	
		// Get composition 
		CompositionContext compositionCtx = getOrCreateComposition(request.getSession());
		// Set content type
		response.setContentType("application/zip");
		
		File file = null;		
		try {
			if(request.getRequestURI().equals("/composition/getDeployment")) {			 
				CreateDeploymentCommand command = new CreateDeploymentCommand();					
				file = compositionCtx.execute(command, null);									
			} 
			else if(request.getRequestURI().equals("/composition/getExport")) {
				ExportCompositionCommand command = new ExportCompositionCommand();
				file = compositionCtx.execute(command, null);  
			}
			else {
				response.setStatus(400);  			
			}
		} catch (Exception e) {			
			e.printStackTrace();
			return;
		}
		
		if(file != null) { 
			sendFile(file, response);
		}
	}
	
	private void sendFile(File file, HttpServletResponse response) throws IOException {
		byte[] buffer = new byte[1024];
		ServletOutputStream out = response.getOutputStream();
		response.setContentLength((int)file.length()); 
		response.addHeader("Content-Disposition", "attachment; filename=" + file.getName()); 			          
		FileInputStream in = new FileInputStream(file); 
		int len;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
	}
}
